package admin.controllers;

import helpers.IdUniqueHelper;
import helpers.StringHelper;

import java.io.IOException;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.data.StaffData;
import admin.data.StoreData;
import admin.forms.StaffForm;

import models.StaffModel;
import models.StoreModel;


public class AddStoreServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		StoreModel storeModel = new StoreModel();
		TreeMap check = new TreeMap();
		
		request.setAttribute("store", storeModel);
		request.setAttribute("check", check);

		try {
			request.getRequestDispatcher("/admin/pages/add_store.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException {
		response.setCharacterEncoding("UTF-8");
		StoreData storeData = new StoreData();
		StoreModel storeModel = new StoreModel();

		String name = (String) request.getParameter("name");
		String address = (String) request.getParameter("address");
		
		TreeMap check = new TreeMap();
		if ((name == null || name.equals(""))) {
			check.put("name", "Bạn chưa nhập tên kho hàng.");
		}
		else {
			if(storeData.getStore(name)!=null) {
				check.put("name", "Kho hàng đã tồn tại.");
			}
		}
		if ((address == null || address.equals(""))) {
			check.put("address", "Bạn chưa nhập địa chỉ kho hàng.");
		}		
		storeModel.setName(name);
		storeModel.setAddress(address);	
		if(check.size() == 0)
	    {
			storeModel.setStoreId(IdUniqueHelper.getId());
			storeData.insertStore(storeModel);			
			request.setAttribute("success", "Thêm kho hàng mới thành công.");
			storeModel = new StoreModel();
	    }
		
		request.setAttribute("check", check);
		request.setAttribute("store", storeModel);
			
		try {
			request.getRequestDispatcher("/admin/pages/add_store.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}
}